﻿using System.Security.Cryptography;
using System.Text.Json;

namespace WYJ.SDK.Web
{
    public class Token
    {
        public static SymmetricCryptoService Coder { get; private set; } = new SymmetricCryptoService(new SymmetricCryptoServiceOption
        {
            Password = new DateTime(2020,1,1).ToLongDateString(),
            SymmetricAlgorithmName = SymmetricAlgorithmName.TripleDES
        });

        public static void Config(string password, SymmetricAlgorithmName name = SymmetricAlgorithmName.Des)
        {
            Coder = new SymmetricCryptoService(new SymmetricCryptoServiceOption
            {
                Password = password,
                SymmetricAlgorithmName = name
            });
        }

        public int NId { get; set; }
        public string SId { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty ;

        public DateTime CreateTime { get; set; } = DateTime.Now;

        public DateTime ExpireTime { get; set; } = DateTime.Now.AddDays(7);


        public virtual bool IsValid()
        {
            return ExpireTime > DateTime.Now;
        }
        public override string ToString()
        {
            string json = JsonSerializer.Serialize(this);
            //json = json.Insert(1, "//\n");
            return Coder.Encode(json);
        }

        public static bool TryParse(string tokenStr,out Token token)
        {
            token = null;
            try
            {
                string json = Coder.Decode(tokenStr);
                token = JsonSerializer.Deserialize<Token>(json)!;
                return true;
            }catch (Exception)
            {
                return false;
            }

        }
    }

}